package com.xiaotu.service.Impl;

import com.xiaotu.mapper.AuthorityRepository;
import com.xiaotu.mapper.CustomerMapper;
import com.xiaotu.mapper.CustomerRepository;
import com.xiaotu.pojo.Authority;
import com.xiaotu.pojo.Customer;
import com.xiaotu.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 对用户数据结合Redis缓存进行业务处理
 */
@Service(value = "jpaCustomerServiceImpl")
public class JpaCustomerServiceImpl implements CustomerService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private AuthorityRepository authorityRepository;
    /**
     * 业务控制,使用唯一用户名查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public Customer getCustomer(String username) {
        Customer customer = null;
        Object o = redisTemplate.opsForValue().get("customer_" + username);
        if (o != null) {
            customer = (Customer) o;
        } else {
            customer = customerRepository.findByUsername(username);
            if (customer != null) {
                redisTemplate.opsForValue().set("customer_" + username, customer);
            }
        }
        return customer;
    }

    @Override
    public List<Authority> getCustomerAuthority(String username) {
        List<Authority> authorities = null;
        Object o = redisTemplate.opsForValue().get("authority_" + username);
        if (o != null) {
            authorities = (List<Authority>) o;
        } else {
            authorities = authorityRepository.findAuthoritiesByUsername(username);
            if (authorities.size()>0){
                redisTemplate.opsForValue().set("authority_"+username, authorities);
            }
        }
        return authorities;
    }
}
